using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Page
{
    [Serializable()]
    public class PageWorkingContent : Csla.BusinessBase<PageWorkingContent>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _pageid = Guid.NewGuid();
        private SmartDate _ModifyDate = new SmartDate(DateTime.Now);
        private int _PlaceholderNumber = 0;
        private string _PlaceholderData = string.Empty;
        private Guid _LastUserid = Guid.NewGuid();
        private int _pageRevision = 0;
        private string _DBConnection = string.Empty;
        private Boolean _HasData = false;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid pageid
        {
            get
            {
                CanReadProperty("pageid", true);
                return _pageid;
            }
            set
            {
                CanWriteProperty("pageid", true);
                //if (value == null)
                //    value = Guid.Empty;
                if (!_pageid.Equals(value))
                {
                    _pageid = value;
                    //PropertyHasChanged("pageid");
                }
            }
        }

        public DateTime ModifyDate
        {
            get
            {
                CanReadProperty("ModifyDate", true);
                return _ModifyDate.Date;
            }
        }

        public string ModifyDateString
        {
            get
            {
                CanReadProperty("ModifyDate", true);
                return _ModifyDate.Text;
            }
            set
            {
                CanWriteProperty("ModifyDate", true);
                if (value == null)
                    value = string.Empty;
                if (!_ModifyDate.Equals(value))
                {
                    _ModifyDate.Text = value;
                    PropertyHasChanged("ModifyDate");
                }
            }
        }

        public int PlaceholderNumber
        {
            get
            {
                CanReadProperty("PlaceholderNumber", true);
                return _PlaceholderNumber;
            }
            set
            {
                CanWriteProperty("PlaceholderNumber", true);
                if (!_PlaceholderNumber.Equals(value))
                {
                    _PlaceholderNumber = value;
                    PropertyHasChanged("PlaceholderNumber");
                }
            }
        }

        public string PlaceholderData
        {
            get
            {
                CanReadProperty("PlaceholderData", true);
                return _PlaceholderData;
            }
            set
            {
                CanWriteProperty("PlaceholderData", true);
                if (value == null)
                    value = string.Empty;
                if (!_PlaceholderData.Equals(value))
                {
                    _PlaceholderData = value;
                    PropertyHasChanged("PlaceholderData");
                }
            }
        }

        public Guid LastUserid
        {
            get
            {
                CanReadProperty("LastUserid", true);
                return _LastUserid;
            }
            set
            {
                CanWriteProperty("LastUserid", true);
                //if (value == null)
                //    value = Guid.Empty;
                if (!_LastUserid.Equals(value))
                {
                    _LastUserid = value;
                    //PropertyHasChanged("LastUserid");
                }
            }

        }

        public int pageRevision
        {
            get
            {
                CanReadProperty("pageRevision", true);
                return _pageRevision;
            }
            set
            {
                CanWriteProperty("pageRevision", true);
                if (!_pageRevision.Equals(value))
                {
                    _pageRevision = value;
                    PropertyHasChanged("pageRevision");
                }
            }
        }

        public string DBConnection
        {
            get
            {
                CanReadProperty("DBConnection", true);
                return _DBConnection;
            }
            set
            {
                CanWriteProperty("DBConnection", true);
                if (value == null)
                    value = string.Empty;
                if (!_DBConnection.Equals(value))
                {
                    _DBConnection = value;
                    PropertyHasChanged("DBConnection");
                }
            }
        }

        public Boolean HasData
        {
            get
            {
                return _HasData;
            }
            set
            {
                _HasData = value;
                //if(value != null)
                //{

                //}
                //else
                //{
                //    _HasData = false;
                //}
            }
        }

        protected override object GetIdValue()
        {
            return _pageid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // modifydate
            //
            //ValidationRules.AddRule(CommonRules.StringRequired, "ModifyDateString");
            //
            // placeholderdata
            //
            //ValidationRules.AddRule(CommonRules.StringRequired, "PlaceholderData");
            //
            // lastuserid
            //
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("LastUserid", 2000));
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in PageWorkingContent
            //AuthorizationRules.AllowRead("id", "PageWorkingContentReadGroup");
            //AuthorizationRules.AllowRead("pageid", "PageWorkingContentReadGroup");
            //AuthorizationRules.AllowRead("modifydate", "PageWorkingContentReadGroup");
            //AuthorizationRules.AllowRead("placeholdernumber", "PageWorkingContentReadGroup");
            //AuthorizationRules.AllowRead("placeholderdata", "PageWorkingContentReadGroup");
            //AuthorizationRules.AllowRead("lastuserid", "PageWorkingContentReadGroup");
            //AuthorizationRules.AllowRead("pagerevision", "PageWorkingContentReadGroup");

            //AuthorizationRules.AllowWrite("modifydate", "PageWorkingContentWriteGroup");
            //AuthorizationRules.AllowWrite("placeholdernumber", "PageWorkingContentWriteGroup");
            //AuthorizationRules.AllowWrite("placeholderdata", "PageWorkingContentWriteGroup");
            //AuthorizationRules.AllowWrite("lastuserid", "PageWorkingContentWriteGroup");
            //AuthorizationRules.AllowWrite("pagerevision", "PageWorkingContentWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in PageWorkingContent
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageWorkingContentViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in PageWorkingContent
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageWorkingContentAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in PageWorkingContent
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageWorkingContentEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in PageWorkingContent
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageWorkingContentDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PageWorkingContent()
        { /* require use of factory method */
        }

        public static PageWorkingContent NewPageWorkingContent()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PageWorkingContent");
            return DataPortal.Create<PageWorkingContent>();
        }

        public static PageWorkingContent GetPageWorkingContent(Guid pageid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a PageWorkingContent");
            return DataPortal.Fetch<PageWorkingContent>(new Criteria(pageid));
        }

        public static void DeletePageWorkingContent(Guid pageid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PageWorkingContent");
            DataPortal.Delete(new Criteria(pageid));
        }

        public override PageWorkingContent Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PageWorkingContent");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PageWorkingContent");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a PageWorkingContent");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid pageid;

            public Criteria(Guid pageid)
            {
                this.pageid = pageid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@pageid", criteria.pageid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.CheckForWorkingDataByPageID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            //dr.Read();
            //_pageid = dr.GetGuid("pageid");
            //_ModifyDate = dr.GetSmartDate("modifydate", _ModifyDate.EmptyIsMin);
            //_PlaceholderNumber = dr.GetInt32("placeholdernumber");
            //_PlaceholderData = dr.GetString("placeholderdata");
            //_LastUserid = dr.GetString("lastuserid");
            //_pageRevision = dr.GetInt32("pagerevision");
            _HasData = dr.Read();
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertPageWorkingData.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@pageid", _pageid);
            DAL.AddParameter("@placeholdernumber", _PlaceholderNumber);
            DAL.AddParameter("@placeholderdata", _PlaceholderData);
            DAL.AddParameter("@lastuserid", _LastUserid);
            DAL.AddParameter("@pagerevision", _pageRevision);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdatePageWorkingData.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@pageid", _pageid);
            DAL.AddParameter("@placeholdernumber", _PlaceholderNumber);
            DAL.AddParameter("@placeholderdata", _PlaceholderData);
            DAL.AddParameter("@lastuserid", _LastUserid);
            DAL.AddParameter("@pagerevision", _pageRevision);
        }

        #endregion //Data Access - Update

        #region Data Access - Delete
        //protected override void DataPortal_DeleteSelf()
        //{
        //    DataPortal_Delete(new Criteria(_id));
        //}

        //private void DataPortal_Delete(Criteria criteria)
        //{
        //    //using (SqlConnection cn = new SqlConnection(Database.powerKBConnection))
        //    //{
        //    //    cn.Open();

        //    //    ExecuteDelete(cn, criteria);

        //    //}//using

        //}

        //private void ExecuteDelete(SqlConnection cn, Criteria criteria)
        //{
        //    using (SqlCommand cm = cn.CreateCommand())
        //    {
        //        cm.CommandType = CommandType.StoredProcedure;
        //        cm.CommandText = "DeletePageWorkingContent";

        //        cm.Parameters.AddWithValue("@id", criteria.id);

        //        cm.ExecuteNonQuery();
        //    }//using
        //}
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
